package cn.hk.xchatroom.config;

import cn.hk.xchatroom.protocol.MessageObject;
import cn.hk.xchatroom.protocol.MessageStatus;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

@ServerEndpoint(value = "/im")
@Component
public class MyWebSocketConfig {
    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static volatile int onlineCount = 0;

    //concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<MyWebSocketConfig> webSocketSet = new CopyOnWriteArraySet<>();

    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;

    private String nickName;

    private int maxSize=5*1024*1024;

    /**
     * 连接建立成功调用的方法*/
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        session.setMaxTextMessageBufferSize(maxSize);

    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //从set中删除
        subOnlineCount();           //在线数减1
        System.out.println("有一连接关闭！当前在线人数为" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息*/
    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("来自客户端的消息:" + message);
        try{
            MessageObject msg=decode(message);
            String cmd=msg.getCmd();
            switch(cmd){
                case MessageStatus.LOGIN:
                    this.setNickName(msg.getNickName());
                    webSocketSet.add(this);     //加入set中
                    addOnlineCount();           //在线数加1
                    System.out.println("有新连接加入！当前在线人数为" + getOnlineCount());
                    //将用户登陆的消息发给所有的其他用户
                    for (MyWebSocketConfig channel : webSocketSet) {
                        //封装一个System的消息对象
                        if(channel == this){
                            msg= new MessageObject(MessageStatus.SYSTEM, System.currentTimeMillis(), msg.getNickName(), "已经与服务器建立连接",webSocketSet.size());
                        }else{
                            msg = new MessageObject(MessageStatus.SYSTEM, System.currentTimeMillis(), msg.getNickName(), msg.getNickName()+"加入了聊天室", webSocketSet.size());
                        }
                        //将消息发送给所有客户端
                        channel.sendMessage(msg);
                    }
                    break;
                case MessageStatus.CHAT:
                    for (MyWebSocketConfig channel : webSocketSet) {
                        if(channel == this){
                            //发送给自己
                            msg.setNickName("SELF");
                        }else{
                            msg.setNickName(channel.getNickName());
                        }
                        channel.sendMessage(msg);
                    }

                    break;
                case MessageStatus.LOGOUT:

                    break;
            }
        }catch(Exception e){
            e.printStackTrace();
        }

    }

    private MessageObject decode(String message) throws Exception{
        return JSON.parseObject(message,MessageObject.class);
    }

    /**
     * 发生错误时调用
     @OnError
     public void onError(Session session, Throwable error) {
     System.out.println("发生错误");
     error.printStackTrace();
     }
     */


     public void sendMessage(String message) throws IOException {
     this.session.getBasicRemote().sendText(message);
     //this.session.getAsyncRemote().sendText(message);
     }
    public void sendMessage(MessageObject message) throws IOException {
        this.session.getBasicRemote().sendText(JSON.toJSONString(message));
        //this.session.getAsyncRemote().sendText(message);
    }

     /**
      * 群发自定义消息
      * */
    public static void sendInfo(String message) throws IOException {
        for (MyWebSocketConfig item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                continue;
            }
        }
    }

    public String getNickName() {
        return nickName;
    }

    public void setNickName(String nickName) {
        this.nickName = nickName;
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        MyWebSocketConfig.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        MyWebSocketConfig.onlineCount--;
    }
}
